using FytSoa.Application.Erp.Param;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using FytSoa.DynamicApi.Attributes;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-bom主表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpBomService : IApplicationService 
{
    private readonly SugarRepository<ErpBom> _thisRepository;
    private readonly SugarRepository<ErpBomProduct> _bomProductRepository;
    private readonly SugarRepository<ErpProduct> _productRepository;
    private readonly SugarRepository<ErpWarehouseProduct> _houseProductRepository;
    public ErpBomService(SugarRepository<ErpBom> thisRepository
    ,SugarRepository<ErpBomProduct> bomProductRepository
    ,SugarRepository<ErpProduct> productRepository
    ,SugarRepository<ErpWarehouseProduct> houseProductRepository)
    {
        _thisRepository = thisRepository;
        _bomProductRepository = bomProductRepository;
        _productRepository = productRepository;
        _houseProductRepository = houseProductRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpBomDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id!=0,m=>m.ProductId==param.Id)
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key))
            .Includes(m=>m.Employee)
            .Includes(m=>m.Product,u=>u.Unit)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpBomDto>>();
    }

    private static readonly Random Random = new ();


    


    /// <summary>
    /// 查询Bom清单&成本
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<List<ErpBomDetailedDto>> GetDetailAsync(long id)
    {
        var res = new List<ErpBomDetailedDto>();
        //读取基本bom信息
        var model = await _thisRepository.GetByIdAsync(id);
        res.Add(new ErpBomDetailedDto()
        {
            Id = id,
            ProductId = model.ProductId,
            ParentId = 0,
            IsBom = true,
            Version=model.Version,
        });
        //根据编号查询bom组成
        var firstBom = await _bomProductRepository.GetListAsync(m => m.BomId == id);
        var bomProductIds = firstBom.Select(m => m.ProductId).ToList();
        //根据产品编号查询bom
        var bomList = await _thisRepository.GetListAsync(m => bomProductIds.Contains(m.ProductId));
        foreach (var item in firstBom)
        {
            var bomModel = bomList.FirstOrDefault(m => m.ProductId == item.ProductId);
            if (bomModel==null)
            {
                res.Add(new ErpBomDetailedDto()
                {
                    Id = Random.Next(100000, 999999),
                    ProductId = item.ProductId,
                    ParentId = id,
                    BomCount = item.Count
                });
            }
            else
            {
                res.Add(new ErpBomDetailedDto()
                {
                    Id = bomModel.Id,
                    ProductId = item.ProductId,
                    ParentId = id,
                    IsBom = true,
                    Version = bomModel.Version,
                    BomCount = item.Count
                });
                var newRes = new List<ErpBomDetailedDto>();
                var newList=await GetBomProductAsync(bomModel,newRes);
                res.AddRange(newList);
            }
        }

        var productIds = res.Select(m => m.ProductId);
        
        //查询产品库存数
        /*var stockProduct=await _houseProductRepository.AsQueryable()
            .Where(m=>productIds.Contains(m.ProductId))
            .GroupBy(m=>m.ProductId)
            .Select(m => new
            {
                m.ProductId,
                Count = SqlFunc.AggregateSum(m.Count)
            })
            .ToListAsync();*/
        
        var productList = await _productRepository.GetListAsync(m => productIds.Contains(m.Id));
        foreach (var item in res)
        {
            var stockCount = 0;
            /*var stockModel = stockProduct.FirstOrDefault(m => m.ProductId == item.ProductId);
            if (stockModel!=null)
            {
                stockCount = stockModel.Count;
            }*/
            var productModel = productList.FirstOrDefault(m => m.Id == item.ProductId);
            if (productModel==null) continue;
            {
                item.Name = productModel.Name;
                item.ProductPrice = productModel.Price;
                item.BomPrice = productModel.Price;
                item.StockCount = stockCount;
            }
        }
        
        
        return res;
    }
    
    /// <summary>
    /// 根据物料编号查询bom组成信息
    /// </summary>
    /// <param name="bom"></param>
    /// <param name="res"></param>
    /// <returns></returns>
    [NonDynamicMethod]
    private async Task<List<ErpBomDetailedDto>> GetBomProductAsync(ErpBom bom ,List<ErpBomDetailedDto> res)
    {
        var bomProductList = await _bomProductRepository.GetListAsync(m => m.BomId == bom.Id);
        foreach (var item in bomProductList)
        {
            res.Add(new ErpBomDetailedDto()
            {
                Id = Random.Next(100000, 999999),
                ProductId = item.ProductId,
                ParentId = bom.Id,
                BomCount = item.Count,
            });
        }
        return res;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpBomDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.Employee)
            .Includes(m=>m.Product)
            .SingleAsync(m=>m.Id==id);
        return model.Adapt<ErpBomDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(ErpBomAddParam param)
    {
        var number = string.Empty;
        var toDay = await _thisRepository.CountAsync(m=>SqlFunc.DateIsSame(m.CreateTime,DateTime.Now));
        number = toDay switch
        {
            < 10 => "00" + (toDay + 1),
            >= 10 and < 100 => "0" + (toDay + 1),
            _ => number
        };
        if (toDay>=99)
        {
            number = (toDay+1).ToString();
        }
        param.Bom.Number = "BOM"+DateTime.Now.ToString("yyyyMMdd")+"-"+number;
        var addBomId=await _thisRepository.InsertReturnSnowflakeIdAsync(param.Bom.Adapt<ErpBom>());
        foreach (var item in param.Product)
        {
            item.BomId = addBomId;
        }
        await _bomProductRepository.InsertRangeAsync(param.Product.Adapt<List<ErpBomProduct>>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyAsync(ErpBomAddParam param)
    {
        await _thisRepository.UpdateAsync(param.Bom.Adapt<ErpBom>());
        await _bomProductRepository.DeleteAsync(m => m.BomId == param.Bom.Id);
        foreach (var item in param.Product)
        {
            item.BomId = param.Bom.Id;
        }
        await _bomProductRepository.InsertRangeAsync(param.Product.Adapt<List<ErpBomProduct>>());
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete,UnitOfWork]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        await _bomProductRepository.DeleteAsync(m => ids.Contains(m.BomId));
    }
}
